<template>
  <div id="customField">
    <ul class="FieldList" v-loading="loading">
      <li class="item" v-for="item in List" :key="item.modulecode">
        <el-col class="title">{{ item.modulename }}</el-col>
        <el-button class="btn" type="primary" @click="AddCustom(item)" round v-if="item.modulecode != 1009">+ 自定义字段</el-button>
        <span v-for="i in item.list" :key="i.id" class="Ibody">
          <span class="spnbox">
            <el-checkbox v-model="i.enable" @change="enableChange(i)" :disabled="!i.iscustom">{{ i.columnname }}</el-checkbox>
          </span>
          <span class="spnIcon">
            <i class="iconfont" @click="operation(i, 'up')">&#xe646;</i>
            <i class="iconfont" @click="operation(i, 'down')">&#xe649;</i>
            <i class="iconfont" @click="operation(i, 'edit', item.modulecode)">&#xe617;</i>
            <i class="iconfont" @click="operation(i, 'del')">&#xe612;</i>
          </span>
        </span>
      </li>
    </ul>
    <!-- 编辑自定义字段 -->
    <el-dialog :title="mtuKent.title" :visible.sync="mtuKent.isShow" width="400px" :close-on-click-modal="false" @closed="handleClose">
      <el-form :model="industryParams" :rules="rules" ref="depForm" label-width="80px" style="padding: 10px 0">
        <el-form-item label="字段名称" prop="columnname">
          <el-input v-model.trim="industryParams.columnname" placeholder="请输入字段名称"></el-input>
        </el-form-item>
        <el-form-item label="字段类型" prop="datatype">
          <el-select v-model="industryParams.datatype" placeholder="字段类型" filterable @change="ChangeTypeFun">
            <el-option v-for="item in dataTypeArr" :key="item.key" :label="item.value" :value="item.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否必填" prop="isRequired">
          <el-switch v-model="industryParams.isRequired"> </el-switch>
        </el-form-item>

        <el-form-item label="选项值" prop="options" v-show="industryParams.datatype == 5">
          <el-input type="textarea" :rows="2" :autosize="{ minRows: 5, maxRows: 20 }" placeholder="请输入选项(每行一个选项)" v-model="industryParams.options"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" type="primary" @click="save" round :loading="isConfirmLoading">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import mixins from "./mixins/index";
export default {
  name: "customField",
  data() {
    return {
      List: [
        {
          name: "基本信息",
          id: 1,
          list: [
            {
              name: "手机号",
              id: 1,
              isShow: false,
            },
          ],
        },
        {
          name: "基础信息",
          id: 2,
          list: [
            {
              name: "手机号",
              id: 1,
              isShow: true,
            },
          ],
        },
      ],
      mtuKent: {
        isShow: false,
        title: "",
      },
      industryParams: {
        columnid: "", //字段ID
        columnname: "", //列名称
        datatype: "", //数据类型
        enable: true, //是否启用
        moduleCode: "", //模块编码
        isRequired: false, //模块编码
        options: "",
      },
      isConfirmLoading: false,
      loading: false,
      dataTypeArr: [],
      thisItem: "",
      rules: {
        columnname: [
          { required: true, message: "请输入字段名称", trigger: "blur" },
          // { min: 1, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        datatype: [{ required: true, message: "请选择字段类型", trigger: "chage" }],
        options: [{ required: false, message: "请输入选项值", trigger: "blur" }],
      },
    };
  },
  computed: {
    ...mapState({
      management: (state) => state.personnel.management,
    }),
  },

  mixins: [mixins],
  methods: {
    ChangeTypeFun() {
      this.industryParams.options = "";
    },
    enableChange(item) {
      // 启用|禁用
      if (!item.allowDisable) {
        this.$message({ type: "warning", message: "预设字段不允许禁用" });
        this.$nextTick(() => {
          item.enable = !item.enable;
        });
        return;
      }
      this.$confirm(`确认${item.enable ? "启用" : "禁用"}此字段吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = {
            columnid: item.columnid,
            enable: item.enable,
          };
          this.$api.customFieldApi.EditFieldEnable(params).then((res) => {
            if (res.data.status == 200) {
              this.$message({ type: "success", message: `${params.enable ? "启用" : "禁用"}成功` });
              this.getData();
            } else {
              this.$message({ type: "warning", message: res.data.message });
            }
          });
        })
        .catch(() => {
          this.$nextTick(() => {
            item.enable = !item.enable;
          });
        });
    },

    operation(item, type, moduleCode) {
      this.thisItem = item;
      switch (type) {
        case "up": // 上移
          this.SetFieldSort(item.columnid, 1);
          break;
        case "down": // 下移
          this.SetFieldSort(item.columnid, 2);
          break;
        case "edit": // 编辑
          if (!item.iscustom) {
            this.$message({ type: "warning", message: "预设字段不允许编辑" });
            return;
          }

          var options = "";
          if (item.datatype == 5) {
            const val = item.options;
            this.oldVal = val;
            let data = [];
            this.oldVal.map((item) => {
              data.push(item.optiondisplay);
            });
            options = this.textareaStr(data);
          }
          this.industryParams = {
            columnid: item.columnid,
            columnname: item.columnname,
            datatype: item.datatype,
            enable: item.enable,
            isRequired: item.isRequired, //模块编码
            moduleCode,
            options: options,
          };

          this.mtuKent = {
            isShow: true,
            title: "自定义字段",
            type: "edit",
          };
          break;
        case "del": // 删除
          if (!item.iscustom) {
            this.$message({ type: "warning", message: "预设字段不允许删除" });
            return;
          }
          this.$confirm("确认删除此字段吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            this.$api.customFieldApi.DeleteFieldExtension({ columnid: item.columnid }).then((res) => {
              if (res.data.status == 200) {
                this.$message({ type: "success", message: "删除成功" });
                this.getData();
              }
            });
          });
          break;

        default:
          break;
      }
    },

    SetFieldSort(columnid, command) {
      // 排序
      this.$confirm(`确认${command == 1 ? "向上" : "向下"}移动此字段吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$api.customFieldApi.SetFieldSort({ columnid, command }).then((res) => {
          if (res.data.status == 200) {
            this.$message({ type: "success", message: "移动成功" });
            this.getData();
          }
        });
      });
    },

    save() {
      // 保存
      this.$refs.depForm.validate((valid) => {
        if (valid) {
          this.mtuKent.type == "add" ? this.saveData() : this.saveEditData();
        }
      });
    },

    saveData() {
      // 新增
      let params = {
        ...this.industryParams,
      };
      params.moduleCode = this.thisItem.modulecode;
      params.options = params.datatype == 5 ? this.onOk() : [];
      this.isConfirmLoading = true;
      this.$api.customFieldApi
        .AddFieldExtension(params)
        .then((res) => {
          if (res.data.status == 200) {
            this.$message({ type: "success", message: "新增成功" });
            this.getData();
          }
          this.mtuKent.isShow = false;
          this.isConfirmLoading = false;
        })
        .catch((err) => {
          this.isConfirmLoading = false;
        });
    },

    saveEditData() {
      // 修改
      let params = {
        ...this.industryParams,
      };
      params.options = this.onOk();
      this.isConfirmLoading = true;
      this.$api.customFieldApi
        .EditFieldExtension(params)
        .then((res) => {
          if (res.data.status == 200) {
            this.$message({ type: "success", message: "编辑成功" });
            this.getData();
          }
          this.mtuKent.isShow = false;
          this.isConfirmLoading = false;
        })
        .catch(() => {
          this.isConfirmLoading = false;
        });
    },

    AddCustom(item) {
      // 新增自定义
      this.thisItem = item;
      this.mtuKent = {
        isShow: true,
        title: "自定义字段",
        type: "add",
      };
    },

    getData() {
      this.isConfirmLoading = true;
      this.loading = true;
      this.getDataList(this.management);
    },

    getDataList(resData) {
      let apiArr = [];
      resData.map((item) => {
        apiArr.push(this.$api.customFieldApi.GetAll({ moduleCode: item.modulecode }));
      });
      Promise.all(apiArr).then((values) => {
        resData.map((item, index) => {
          item.list = values[index].data.data;
        });
        this.List = resData;
        this.loading = false;
        this.isConfirmLoading = false;
      });
    },

    initialize() {
      this.$api.optionsManage.GetEnumDataOptiont({ metaTypeCode: "Basics_fieldType" }).then((res) => {
        this.dataTypeArr = res.data.data;
      });
    },
    // SetFieldSort
  },

  mounted() {
    this.getData();
    this.initialize();
  },
};
</script>

<style lang="less" scoped>
#customField {
  .FieldList {
    .item {
      margin-bottom: 30px;
      .title {
        height: 40px;
        line-height: 40px;
        background-color: #f5f8fd;
        font-size: 15px;
        color: #333;
        border-radius: 3px;
        padding-left: 25px;
        margin-bottom: 20px;
      }
      .btn {
        margin-left: 25px;
        margin-bottom: 15px;
      }
      .Ibody {
        width: 500px;
        height: 40px;
        display: flex;
        align-items: center;
        margin-left: 25px;
        border-bottom: 1px solid rgb(245, 243, 243);
        > span {
          display: inline-block;
        }
        .spnbox {
          width: 80%;
        }
        .spnIcon {
          width: 20%;
          .iconfont {
            color: #b0b7c2;
            cursor: pointer;
            font-size: 17px;
            margin-left: 8px;
            &:hover {
              color: #5a93ff;
            }
          }
        }
      }
    }
  }
}
</style>
